/**
 * This is compatible with Error class from _error.php
 * It provides a way how to show an error message using javascript.
 * It transfers error messages from the bottom of the page
 * (written by php application) to appopriate place - at the top.
 */
var errormsg = null;

function Errormsg() {
	this.node = document.getElementById("errormsg");
	this.template = document.getElementById("_TEMPLATE_ERRORMSG_");
	this.msgBoxes = [];
	/**
	 * Actual count of visible error messages 
	 */
	this.count = 0;
}
Errormsg.getErrormsg = function() {
	if (typeof(errormsg) == "undefined" || errormsg == null) {
		errormsg = new Errormsg();
	}
	return errormsg;
};
Errormsg.prototype.addError = function(msg, boxId) {
	this.addMsg('<span class="bold" >Error:</span> ' + msg, boxId);
};
Errormsg.prototype.addWarning = function(msg, boxId) {
	this.addMsg('<span class="bold" >Warning:</span> ' + msg, boxId);
};
Errormsg.prototype.addMsg = function(msg, boxId) {
	if (typeof(msg) == "undefined" || msg == "" || msg == null) {
		this.hideBox(boxId);
	} else if (this.msgBoxes[boxId]) {
		Errormsg.writeMsgIntoABox(msg, this.msgBoxes[boxId]);
		this.count++;
		this.node.appendChild(this.msgBoxes[boxId]); 
	} else {
		var msgBox = this.cloneTemplate();
		Errormsg.writeMsgIntoABox(msg, msgBox);
		this.msgBoxes[boxId] = msgBox;
		this.count++;
		this.node.appendChild(msgBox);
	}
	window.location = "#errormsg";
	
};
Errormsg.prototype.cloneTemplate = function() {
	var msgNode = this.template.cloneNode(true);
	msgNode.style.visibility = "";
	msgNode.style.position = "";
	msgNode.removeAttribute("id");
	return msgNode;
};
Errormsg.prototype.removeBox = function(boxId) {
	if (this.msgBoxes[boxId]) {
		try {
			this.node.removeChild(this.msgBoxes[boxId]);
			this.count--;
		} 
		catch (e) {
		}
		finally {
			this.msgBoxes.pop(this.msgBoxes[boxId]);
		}
	}
};
Errormsg.prototype.hideBox = function(boxId) {
	if (this.msgBoxes[boxId]) {
		try {
			this.node.removeChild(this.msgBoxes[boxId]);
			this.count--;
		} catch(e) {
		}
	}
};
Errormsg.prototype.countOfMsgs = function() {
	return this.count;
};
Errormsg.writeMsgIntoABox = function(msg, msgBox) {
	msgBox.innerHTML = msg;
};
Errormsg.moveErrormsgBoxesFromBottomToUp = function() {
	var errormsg = Errormsg.getErrormsg();
	var nodeBottom = document.getElementById("errormsg-footer");
	
	while (nodeBottom.hasChildNodes()) {
		errormsg.node.appendChild(nodeBottom.removeChild(nodeBottom.firstChild));
	}
}